﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SystemControllers;
using eTMS.Controllers;
using eTMS.Commons;
using SystemControllers.MenusService;
using SystemControllers.RolesService;

namespace eTMS.Forms.Systems
{
    public partial class FrmRoles : eTMS.Controls.BaseForm
    {
        public FrmRoles()
        {
            InitializeComponent();
        }
        #region Variables
        private RolesController controller = new RolesController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage()
        {
            this.Text = RolesStringMapping.Roles;
            this.labelFormTitle.Text = Constants.APP_ADMINISTRATION + " " + RolesStringMapping.Roles;
            this.groupBoxDetail.Text = Constants.APP_DETAIL;
            this.groupBoxList.Text = Constants.APP_LIST;
            this.ColumnSTT.HeaderText = Constants.APP_INDEX;
            labelRoleCode.Text = RolesStringMapping.RoleCode;
            ColumnRoleCode.HeaderText = RolesStringMapping.RoleCode;
            labelRoleName.Text = RolesStringMapping.RoleName;
            ColumnRoleName.HeaderText = RolesStringMapping.RoleName;
            labelRoleDescription.Text = RolesStringMapping.RoleDescription;
            ColumnRoleDescription.HeaderText = RolesStringMapping.RoleDescription;
            labelPermission.Text = RolesStringMapping.Permission;

        }
        //Get entity selected from datagrid
        private RolesEntity GetObject()
        {
            RolesEntity o = controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
            controller.RolesObject = o;
            return o;
        }
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows()
        {
            List<DataRow> ls = new List<DataRow>();
            for (int i = 0; i < gridData.SelectedRows.Count; i++)
            {
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
            return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow()
        {
            DataRow row = GetDataRow(gridData.SelectedRows[0].Index);
            return row;
        }
        //Get the selected data row in datagrid
        private DataRow GetDataRow(int index)
        {
            DataRow row = ((DataRowView)gridData.Rows[index].DataBoundItem).Row;
            return row;
        }
        //Reset all textbox
        private void ClearScreen()
        {
            txtRoleCode.Text = "";
            txtRoleName.Text = "";
            txtRoleDescription.Text = "";
            errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked)
        {
            ucCommand.LockControl(IsLocked);
            txtRoleCode.ReadOnly = IsLocked;
            txtRoleName.ReadOnly = IsLocked;
            txtRoleDescription.ReadOnly = IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(RolesEntity o)
        {
            o.RoleCode = Convert.ToString(txtRoleCode.Text);
            o.RoleName = Convert.ToString(txtRoleName.Text);
            o.RoleDescription = Convert.ToString(txtRoleDescription.Text);
            if (Flag == ACTIONENUM.AddNew)
            {
                o.RoleType = 1;
            }
        }
        //Bind data from object to control in screen
        private void CopyToSreen(RolesEntity o)
        {
            if (!o.IsNullRoleCode)
            {
                txtRoleCode.Text = Convert.ToString(o.RoleCode);
            }
            if (!o.IsNullRoleName)
            {
                txtRoleName.Text = Convert.ToString(o.RoleName);
            }
            if (!o.IsNullRoleDescription)
            {
                txtRoleDescription.Text = Convert.ToString(o.RoleDescription);
            }
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen()
        {
            bool result = true;
            if (!result)
            {
                ShowInfo(Constants.MSS_REQUIRE_FIELD);
            }
            return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo()
        {
            if (gridData.SelectedRows.Count == 0) return;
            if (gridData.SelectedRows[0].Index < gridData.Rows.Count)
            {
                RolesEntity o = GetObject();
                CopyToSreen(o);
                controller.LoadMenuRoles();
                ACTIONENUM curAction = Flag;
                Flag = ACTIONENUM.Loading;
                LoadChecked(treeMenu.Nodes[0]);
                Flag = curAction;
            }
        }
        private void LoadChecked(TreeNode node)
        {
            foreach (TreeNode treeNode in node.Nodes)
            {
                MenusEntity oMenu = (MenusEntity)treeNode.Tag;
                treeNode.Checked = controller.IsMenuInRole(oMenu.Menu_ID);
                LoadChecked(treeNode);
            }
        }
        #endregion
        #region Business
        private void LoadMenuItem(int MenuParent_ID, TreeNodeCollection collection)
        {
            foreach (MenusEntity menusEntity in controller.FindMenuByParent(MenuParent_ID))
            {
                TreeNode node = new TreeNode();
                node.Text = menusEntity.MenuTitle;
                node.Tag = menusEntity;
                node.ImageIndex = 0;
                collection.Add(node);
                LoadMenuItem(menusEntity.Menu_ID, node.Nodes);
            }
        }
        private void LoadMenus()
        {
            TreeNode node = new TreeNode();
            node.Text = Constants.APP_ALL;
            treeMenu.Nodes.Add(node);
            LoadMenuItem(0, node.Nodes);
            node.Expand();
        }
        //AddNew data to database
        private bool AddNewData()
        {
            bool rval = false;
            controller.ResetObject();
            CopyFromSreen(controller.RolesObject);
            rval = controller.AddNew();
            if (rval)
            {
                DataRow row = controller.Table.NewRow();
                row["STT"] = controller.Table.Rows.Count + 1;
                controller.MapObjectToDataRow(row);
                controller.Table.Rows.Add(row);
                gridData.DataSource = null;
                gridData.DataSource = controller.Table;
                AddMenus();
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {
            DataRow row = GetSelectedDataRow();
            controller.LoadObject((Int32)row["Role_ID"]);
            CopyFromSreen(controller.RolesObject);
            bool rval = controller.Update();
            if (rval)
            {
                controller.MapObjectToDataRow(row);
                gridData.InvalidateRow(gridData.SelectedRows[0].Index);
                AddMenus();
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls = GetSelectedDataRows();
            if (ls.Count == 0) return false;
            bool rval = true;
            try
            {
                gridData.DataSource = null;
                foreach (DataRow row in ls)
                {
                    if (controller.DeleteByID((Int32)row["Role_ID"]))
                    {
                        this.controller.Table.Rows.Remove(row);
                    }
                    else
                    {
                        rval = false;
                    }
                }
                this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch
            {
                return false;
            }
            return true;
        }
        private void AddMenus()
        {
            List<int> lsChecked = new List<int>();
            GetCheckedMenus(lsChecked, treeMenu.Nodes[0]);
            controller.AddMenusToRole(lsChecked);
        }
        private void GetCheckedMenus(List<int> lsMenu_ID, TreeNode pNode)
        {
            foreach (TreeNode node in pNode.Nodes)
            {
                if (node.Checked)
                {
                    MenusEntity oMenu = (MenusEntity)node.Tag;
                    lsMenu_ID.Add(oMenu.Menu_ID);
                }
                GetCheckedMenus(lsMenu_ID, node);
            }
        }
        #endregion
        #region DataBinding
        //Bind data to datagrid
        private void LoadData()
        {
            gridData.AutoGenerateColumns = false;
            if (UsersController.User.UserType != 0)
                controller.Table.DefaultView.RowFilter = "RoleType=1";
            gridData.DataSource = controller.Table;
            gridData.AutoResizeColumns();
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmRoles_Load(object sender, EventArgs e)
        {
            LoadLanguage();
            LoadMenus();
            LoadData();
            LockScreen(true);
        }
        private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindInfo();
        }
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
            ClearScreen();
            LockScreen(false);
            Flag = ACTIONENUM.AddNew;
            txtRoleCode.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if (!Confirm(Constants.MSS_CONFIRM_DELETE)) return;
            DeleteData();
            this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag = ACTIONENUM.Edit;
            txtRoleCode.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
            if (!ValidateScreen())
                return;
            if (Flag == ACTIONENUM.Edit)
            {
                if (UpdateData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else
            {
                if (AddNewData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag = ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
            LockScreen(true);
            if (Flag == ACTIONENUM.AddNew)
            {
                ClearScreen();
                ucCommand.SetFocusAddNew();
            }
            else if (Flag == ACTIONENUM.Edit)
            {
                BindInfo();
                this.gridData.Focus();
            }
            Flag = ACTIONENUM.None;
        }
        #endregion
        private void treeMenu_BeforeCheck(object sender, TreeViewCancelEventArgs e)
        {
            if ((Flag != ACTIONENUM.AddNew) && (Flag != ACTIONENUM.Edit) && (Flag != ACTIONENUM.Loading))
            {
                e.Cancel = true;
                return;
            }
        }
        private void treeMenu_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if ((Flag == ACTIONENUM.AddNew) || (Flag == ACTIONENUM.Edit))
            {
                foreach (TreeNode node in e.Node.Nodes)
                {
                    node.Checked = e.Node.Checked;
                }
            }
        }
    }
}
